/*
 * @Description: 基础接口服务
 * @Author: wws1993
 * @Date: 2020-11-25 18:30:15
 * @LastEditTime: 2020-12-11 11:37:40
 * @LastEditors: wws1993
 * @FilePath: \TODO-MANAGER\src\service\BaseModal.ts
 */

import Service from './ServiceForLocalStorage';

export default class BaseModal {
  /** 表名 */
  private key!: string;

  constructor(key: string) {
    this.key = key;
  }
  /** 增 */
  protected create(data: anyObject) {
    let storage = Service.get(this.key);
    storage = storage ? [...storage, {...data, id: storage.length + 1}] : [{...data, id: 1}];

    return Service.set(this.key, storage);
  }
  /** 删 */
  protected delete(id: number) {
    return new Promise((resolve, reject) => {
      const storage = Service.get(this.key);

      if (storage) {
        const idx = storage.findIndex(k => k.id === id);

        if (idx !== -1) {
          storage.splice(idx, 1);
          Service.set(this.key, storage).then(() => resolve()).catch(err => reject(err));
        } else {
          reject('未索引到');
        }
      } else {
        reject('无数据源');
      }
    });
  }
  /** 改 */
  protected update(data: anyObject) {
    const storage = Service.get(this.key);
    if (storage) {
      const idx = storage.findIndex(k => k.id === data.id);
      storage.splice(idx, 1, data);
      return Service.set(this.key, storage);
    } else {
      return this.create(data);
    }
  }
  /** 查 */
  protected query(): Promise<anyObject[] | null> {
    return new Promise((resolve, reject) => {
      resolve(Service.get(this.key));
    });
  }
  /** 生成hash */
  private getHash() {
    const lib = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
    let str = Service.BASEHEADE;

    for (; str.length <= 28; ) {
      str += lib[Math.round(Math.random() * lib.length)];
    }

    str += 'DDDD';

    return str;
  }
}
